import requests
from lxml import etree
import time
import os
import random
from random import randint
import threading
import mysql.connector
from datetime import datetime
from ebaysimple import   get_ebay_data
from aliexpress import captureali
import re
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
from PyQt5.QtCore import QPoint
from xrates import getrate
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtCore import Qt  # 正确导入Qt
from datetime import datetime, timedelta, time as datetime_time
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
import sys
from concurrent.futures import ThreadPoolExecutor
import threading
from mysql.connector import pooling
print(mysql.connector.__version__)
import queue
from mysql.connector import Error as MySQLError  # 正确的导入方式
from followth_node import heartnode,getnodeorder,getnodescount   ,get_disk_serial_simple 
def getconn(pool):
    conn = pool.get_connection()
    return conn
def downloaddata(pool,diskid):
        conn=pool.get_connection()
        lock = threading.Lock()
        inat = 1
        executor = ThreadPoolExecutor(max_workers=3)
        # unfollownotdownload = get_config_value(conn,'unfollownotdownload',1)
        try:
            while True:
                    # 在这里放置你要执行的任务代码，这里以打印当前时间为例
                print('爬虫程序10秒执行一次')
                print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                lock.acquire()
                # conn = getconn()
                # if capture_do(conn):
                try:
                    downloadrate2(pool,conn)
                    process_1(pool,conn,executor,diskid)
                except Exception as e:
                    print('downloadrate2',e)
                    if isinstance(e, MySQLError):
                       conn=pool.get_connection()
                
                finally:
                    lock.release()
                time.sleep(10)

        except Exception as e:
            print(e)
            inat = inat + 1
        finally:
            closeconn(conn)

    # cookie失效，从浏览器中获取
# 读取当前文件夹 alicookie
splitchar = '->'
# config = {
#     "user": "root",
#     "password": "Zb_200407",
#     "host": "gz-cdb-d4j7h16x.sql.tencentcdb.com",
#     "database": "eas",
#     'port':22333
# }
# a=234234
# a+=234
ebay_input_str = '__uzma=c0a63d31-913c-47d6-802f-40e2ac211ed7; __uzmb=1732709484; __uzme=4401; AMP_MKTG_f93443b04c=JTdCJTdE; __ssds=2; __uzmaj2=7f7324ad-af4b-486c-863c-81d76fc4e671; __uzmbj2=1732709491; __uzmlj2=V//yL6hJ/4Z8vUgq1NXXzn5wHROJkH8hUTHa7AYxG/k=; _gcl_au=1.1.1748374085.1732709495; _scid=76u433iAZav__LdjnjKTg_awdFriRmlV; _ScCbts=%5B%5D; _fbp=fb.1.1732718953212.684100462467222093; _pin_unauth=dWlkPU0yRXpPV1ZrTmpJdE1Ea3laUzAwTXpNNUxUazFObVV0TUdGbU5qUXlNRFF5TkRGbQ; __ssuzjsr2=a9be2cd8e; ak_bmsc=65A6C95681CCA3629785BC913F2E25BB~000000000000000000000000000000~YAAQbATYF++iSkGTAQAAXzKccBlnUHgUo/LrVbccFANLzHwvY/YREcvCMtH+DosQWEzuc1aVkNc8GEZgGup7mOtPD59In18TXKHkeCq7YVHYo9gUqBLaJ3JfpvUolkC8LhB3+1QvDKOOiWGeMrHz42uaJZccOEc/3Mt+FWfyJIe9oRaFuICQ+fTsBDkEvm3E7V0r/040qXAx8POaT+eTjQdZKS+wjcWCa0jp4i6pKhSCCmNzZq8EChaKZe+KAqbQ67go3IB966bsbrmq6FrqsaJbdODg6QRj41464xr2gQl47ZUIZCyv1Q23EIM7EeVNLfPstKxBIMaS+hS+kvg0CD0TV+a5Xf+1QEA/plhZkmCnFUcz0bkJESDfgBtotLVjdsWIyG4cEig=; utag_main__sn=4; utag_main_ses_id=1732765034062%3Bexp-session; utag_main__ss=0%3Bexp-session; AMP_f93443b04c=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjI2NTg1YTI1OS0yN2ExLTQzZDUtOGNkMy1iZWZlYzgzMDQzYWMlMjIlMkMlMjJzZXNzaW9uSWQlMjIlM0ExNzMyNzY0NzE3MjI2JTJDJTIyb3B0T3V0JTIyJTNBZmFsc2UlMkMlMjJsYXN0RXZlbnRUaW1lJTIyJTNBMTczMjc2NTkzNjc2NyUyQyUyMmxhc3RFdmVudElkJTIyJTNBMzclMkMlMjJwYWdlQ291bnRlciUyMiUzQTYlN0Q=; s=CgAD4ACBnSTp1NmQ4ODdlZjMxOTMwYTJhMDNhZGNkYjE2ZmZmZjNlNDFmYECb; __deba=6LC1Y1kednUB8L706-mtOVGbSS-_UGric6wfDMIa6_-4bxJZxNWUu1oHyWcTs65UdUJqTQXGeS5Wh72tk9p5u8ZcjNK1sibxAytUuGnmPWz2A2pFQE3am8tA1LsAzahJklftaoZK88AqkxSczirgag==; utag_main__se=12%3Bexp-session; utag_main__st=1732767758525%3Bexp-session; utag_main__pn=12%3Bexp-session; __gads=ID=814eea2281047449:T=1732709494:RT=1732765960:S=ALNI_Mbi0GaU8XJ34S6QBS5Mq_D91OMdoQ; __gpi=UID=00000f79249a1e83:T=1732709494:RT=1732765960:S=ALNI_MYSokInL0TbsGtn9kNjJ_DTrTbZaA; __eoi=ID=c50319ce0fda5439:T=1732709494:RT=1732765960:S=AA-AfjbtYc9PggmPW_BlN3wwdf5Z; cto_bundle=9xxaw19EM2xqVVE0cmxOd1pLMTFJR1oxYTczRHpDUCUyQlJjY09uS2V5R2xQMHdEdjBPckM0cThXcmJXNm53dEZpJTJGZ0J3U0c3a3Q4TnQxb09mRDBYRERRNTk4OHZQJTJGNFVLVWlzWW0lMkYyaVZDaEVCOU1LT0hIaG9IbVNNeG04Ym5aWWxzY1AySk5wM3FMUkpTOTlmWm9IJTJCciUyQkV6SnclM0QlM0Q; _scid_r=_iu433iAZav__LdjnjKTg_awdFriRmlVWSqg1w; __uzmc=4619317519497; __uzmd=1732766020; __uzmf=7f6000b2b8bc82-a7a5-455e-b77a-20cdd5e5f994173270948414156536721-7303b338308147b5175; bm_sv=37C8BA606DCF326A7361BF672311728C~YAAQp/w7F1X/u2+TAQAA+DXncBkWfPxEW6xU7wGn2s4XEpYHwJpbFkXi9Y941Kt5NDyuJgMKevN/vLYRVoNV5EDbPUW6Z5YYqWx3Ho2IbyxeBqm+zHelpca86OoHXqpaQ+QHAuDDe+HVFhav7uYuLfsnJm8aP+haBsX61gzAi+TCAGchuPRoegyOPAkbSvueFsDdUQ8ZMuKcAYAKo1BiSKFdumvE+1gqypBDjbPFBFpjlmrOQEa3/qanmLoV+GM=~1; ds2=asotr/b8_5azzzzzzz^; ebay=%5Ejs%3D1%5Esbf%3D%23000000%5Epsi%3DA5gh94ks*%5E; __uzmcj2=115439470280; __uzmdj2=1732766025; __uzmfj2=7f6000b2b8bc82-a7a5-455e-b77a-20cdd5e5f994173270949163956533438-d16def096f29543c94; ns1=BAQAAAZJU03gwAAaAANgAU2kpHMxjNjl8NjAxXjE3MzI3MDk0OTA3NTdeXjFeM3wyfDV8NHw3fDEwfDQyfDQzfDExXl5eNF4zXjEyXjEyXjJeMV4xXjBeMV4wXjFeNjQ0MjQ1OTA3NWoR/+Iw6oLvSV2scNVm1KOMQYiT; nonsession=BAQAAAZJU03gwAAaAADMABmkpHMw1MjUyMDAAygAgawpQTDZkODg3ZWYzMTkzMGEyYTAzYWRjZGIxNmZmZmYzZTQxAMsAA2dH8FQxMTLd6l6HRnnqAqCNL443vxwklatw/w**; dp1=bu1p/QEBfX0BAX19AQA**6b0a504c^pbf/%23e00060000000000000000069291ccc^bl/CN6b0a504c^'
print("Cookie 已加载")


def downloadrate2(pool,conn):
    cursor_a=None  
    try:
        cursor_a=conn.cursor()
    except Exception as e:
        print('连接数据库出错',e)
        try:
            conn.close()
            
        except Exception as e:
            print('连接数据库出错',e)
        conn=pool.get_connection()
        cursor_a=conn.cursor()    
    query = f"select * from sku_keywords_history where keywords='downloadrate'  and datediff(opdate,now())= 0"
    cursor_b = conn.cursor()
    cursor_c = conn.cursor()

    cursor_a.execute(query)
    # 获取所有结果
    results_a = cursor_a.fetchall()

    b_cap = 0
    count = len(results_a)
    rates = []
    if len(results_a)==0 :
        rates = getrate()
        print('需要下载汇率')
    else:
        print('不需要下载汇率')
        return 

    sql2='select * from rates'
    cursor_c.execute(sql2)
    results_c = cursor_c.fetchall()
    if len(results_c) <5:
        try:
            for rt in rates:
                cur1 = rt['currency']
                cur2 = rt['exchange_rate']
                 
                query = f"insert into rates(currency_name,currency_simplename,rate,opdate)  values('{cur1}','{cur1}',{cur2},now())"
                rows_affected=cursor_a.execute(query)
                conn.commit()

        except Exception as e:
            print(e) 
    sql2='select * from rates'
    cursor_c.execute(sql2)
    results_c = cursor_c.fetchall()
    if len(results_c) > 0:
        
        for rt in rates:
            try:
                cur1 = rt['currency']
                cur2 = rt['exchange_rate']
                sql = f' update  rates set rate="{cur2}"  ,opdate=now() where currency_name="{cur1}"'
                # cursor_c = conn.cursor()
                print(sql)
                # rows_affected = cursor_c.execute(sql)
                with conn.cursor() as cursor:
                    cursor.execute(sql)
                    # 在with语句块内提交事务，确保数据插入生效
                    conn.commit()
            except Exception as e:
                print('downloadrate2',e)

            

    query = f"insert into sku_keywords_history(keywords,opdate)  values('downloadrate',now())"
            # cursor_a = conn.cursor()
    cursor_b = conn.cursor()
    cursor_b.execute(query)
    conn.commit()
    cursor_b.close()
    cursor_a.close()
    cursor_c.close()



def getwhitelist(conn, shoptype):
    sql = f'select distinct shop_type,shop_name from  shopwhite_list where shop_type="{shoptype}"'
    cursor_a = conn.cursor()
    cursor_a.execute(sql)
    # 获取所有结果
    results_a = cursor_a.fetchall()
    whitelist = []
    for row in results_a:
        shopname = row[1]
        whitelist.append(shopname)
    cursor_a.close()
    return whitelist

   
def dictexists(my_list, target_str):
    found = False
    target_str = target_str.lower().replace(' ', '')

    for element in my_list:
        element = element.lower().replace(' ', '')
        if element in  target_str:
            found = True
            break
    return found

# def getconn():
#     return mysql.connector.connect(**config)

def closeconn(conn):
    conn.close()

def getexcept(emsg):
    spec = [
        "'"
        '<', '>', '$', '*', '&', '%', '.', '"', '+', '-', '@', '"', '\\',
        '(', ')', ' ', '#', '.', '//', '#'
    ]
    for sp in spec:
        if sp in emsg:
            emsg = emsg.replace(sp, '')
    emsg = emsg.replace('"', '')
    return emsg.strip()

def getuser_bykeywords(conn, keywords,shoptype):
    """
    获取与指定关键词相关的所有用户名
    
    Args:
        conn: 数据库连接
        keywords: 关键词
        
    Returns:
        list: 用户名列表
    """
    try:
        cursor = conn.cursor(dictionary=True)
        
        # 使用参数化查询
        query = f"SELECT DISTINCT username FROM sku_keywords WHERE keywords = '{keywords}' and {shoptype}=1"
        cursor.execute(query)
        
        # 获取所有结果
        results = cursor.fetchall()
        
        # 提取用户名列表
        usernames = [row['username'] for row in results if row['username']]  # 过滤掉空值
        
        return usernames
        
    except Exception as e:
        print(f"Error in getuser_bykeywords: {str(e)}")
        return []
        
    finally:
        cursor.close()
def get_configure(conn):
    try:
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM configure")
        result = cursor.fetchall()
        return result
    finally:
        cursor.close()
def process_1(pool,conn,executor,diskid):
    # 读取数据库
    # 输出数据给capture
    # 连接数据库配置
    # 连接到数据库
    # 查询表A的语，这里假设表A有id和name两个字段，你可根据实际表结构修改
    current_time_stamp = time.time()
    # 将时间戳转换为本地时间的结构体
    local_time_struct = time.localtime(current_time_stamp)
    # 提取小时、分钟、秒
    hour = local_time_struct.tm_hour
    minute = local_time_struct.tm_min
    intnewkeywords=1
    #当前处理的是否当日新增关键词
    second = local_time_struct.tm_sec
    
    hrandom = random.randint(1, 30)
    print(f"当前时间是：{hour}时{minute}分{second}秒")
    current_date = datetime.now().date()
    target_date = current_date + timedelta(days=0)
    t8=datetime.combine(target_date, datetime_time(8, 0, 0))
    t11=datetime.combine(target_date, datetime_time(11, 0, 0))
    t20=datetime.combine(target_date, datetime_time(13, 0, 0))
    t23=datetime.combine(target_date, datetime_time(16, 0, 0))
    t1=None
    t2=None
    if hour <=11 and hour >=8:
            t1=t8
            t2=t11
    elif hour <=23 and hour >=17:
            t1=t20
            t2=t23     
    cursor=None  
    try:
        cursor=conn.cursor()
    except Exception as e:
        print('连接数据库出错',e)
        try:
            conn.close()
            
        except Exception as e:
            print('连接数据库出错',e)
        conn=pool.get_connection()
        cursor=conn.cursor()    

    current_time = datetime.now()
    print(current_time) 
    configure=get_configure(conn)
    intnewkeywordssleep=1
    intoldkeywrodssleep=29
    inthoursdiff=20
    for row in configure:
        print(row)
        if row['cfgcode']=='newkeywordssleep':
            intnewkeywordssleep=int(row['cfgvalue'])
        if row['cfgcode']=='oldkeywordssleep':
            intoldkeywrodssleep=int(row['cfgvalue'])
        if row['cfgcode']=='hoursdiff':
            inthoursdiff=int(row['cfgvalue'])
            
    heartnode(conn,diskid)
    nodeorder=getnodeorder(conn,diskid)
    print('节点顺序',nodeorder)
    count=getnodescount(conn)   
    print('节点数量',count)
    query = f"""SELECT distinct keywords,ebay,ali FROM sku_keywords where  not exists
                (select * from sku_keywords_history where    keywords=sku_keywords.keywords
                and   username =sku_keywords.username )"""
    if count>1:
        query=query + f" and  mod(id,{count} )={nodeorder}"
    query+=' limit 10'
    print(query)
    cursor_a = conn.cursor()
    cursor_a.execute(query)
    # 获取所有结果
    results_a = cursor_a.fetchall()
    print(results_a)
    if len(results_a) ==0:
        intnewkeywords=0
        query = f"""SELECT DISTINCT sk.keywords, sk.ebay, sk.ali 
                    FROM sku_keywords sk
                    WHERE EXISTS (
                        SELECT 1 
                        FROM sku_keywords_history skh
                        WHERE skh.keywords = sk.keywords
                    )
                    AND NOT EXISTS (
                        SELECT 1 
                        FROM sku_keywords_history skh
                        WHERE skh.keywords = sk.keywords
                        AND TIMESTAMPDIFF(HOUR, skh.opdate, NOW()) <={inthoursdiff} and DATEDIFF(skh.opdate,now())=0
                    )"""
        if count>1:
            query=query + f" and  mod(sk.id,{count} )={nodeorder}"
        query+=' limit 10'
        print(query)
        cursor_a = conn.cursor()
        cursor_a.execute(query)
        intsleeptime=30
        results_a = cursor_a.fetchall()
    data_to_insert = []
    capkeywords_ali = []
    capkeywords_ebay = []
    links = []
    exceptitems = []
    link_withkey = []
    for index,results in enumerate( results_a):
        key2 = results[0]
        ebay = results[1]
        ali = results[2]
        current_time_stamp = time.time()
        # 将时间戳转换为本地时间的结构体
        local_time_struct = time.localtime(current_time_stamp)
        # 提取小时、分钟、秒
        hour = local_time_struct.tm_hour
        minute = local_time_struct.tm_min
        second = local_time_struct.tm_sec
        hrandom = random.randint(1, 30)
        print(f"当前：{hour}时{minute}分{second}秒->",f'{index}/{len(results_a)} 个关键词记录{key2}')
        # print(f'{index}/{len(results_a)} 个关键词记录{key2}')

        a = 1
        b = 0
        try:
            # 如果需要抓取，看看是否已经加入了抓取字典数组
            if ebay == 1 and dictexists(capkeywords_ebay, key2) == 0:
                # 同一个关键词可能有多个用户使用
                capkeywords_ebay.append(key2)
                link1 = get_ebay_data(key2, 2)
                # links.extend(link1)
                usernames=getuser_bykeywords(conn,key2,'ebay')

                linkkey={
                    "key": key2,
                    "shoptype": "ebay",
                    "links": link1,
                    'username':usernames
                }
                # link_withkey.append(linkkey)
                process_2(pool,conn, linkkey)
                
                # if intnewkeywords==1:
                #     time.sleep(intnewkeywordssleep)
                # else:
                #     time.sleep(intoldkeywrodssleep)

        except Exception as e:
            print(f"抓取ebay出错：{e}")
            # exceptitems.append(('ebay', key2, e))
            sql = f" insert into crawlexcept(shop_type,keywords,exceptcon)  values('ebay','{key2}','{getexcept(str(e))}')"
            exceptitems.append(sql)
        if ali == 1 and dictexists(capkeywords_ali, key2) == 0:
            # capkeywords_ali.append(key2)
            usernames=getuser_bykeywords(conn,key2,'ali')

            try:
                link1 = captureali(key2)
                linkkey={
                    "key": key2,
                    "shoptype": "ali",
                    "links": link1,
                    'username':usernames
                }
                process_2(pool,conn, linkkey)
                # executor.submit(process_2, conn, linkkey)
                if intnewkeywords==1:
                    time.sleep(intnewkeywordssleep)
                else:
                    time.sleep(intoldkeywrodssleep)
            except Exception as e:
                time.sleep(1)
                print(f"抓取aliexpress.com出错：{e}")
            #     sql = f" insert into crawlexcept(shop_type,keywords,exceptcon)  values('ali','{key2}','{getexcept(str(e))}')"
            #     exceptitems.append(sql)
    if intnewkeywords==1:
        time.sleep(intnewkeywordssleep)
    else:
        time.sleep(intoldkeywrodssleep)# executor.submit(process_2, conn, linkkey)
    mycursor = None
    if exceptitems:
        mycursor = conn.cursor()

    for exp in exceptitems:
        mycursor.execute(exp)
    if exceptitems:

        conn.commit()
        mycursor.close()
    cursor.close()
    cursor_a.close()
    return link_withkey

# 关闭游标和连接


def process_2(pool,conn, link):
    # 输入的是链接，内容是关键词，网站类型
    # 关键词表keywordsid=""
    # links包括了
    # type='ebay'
    # # 或者 'ali'
    # skuid=''
    # title =''
    # pic=''
    # price=0.0
    # productid=''
    # link=''
    # 去抓取；然后更新相关信息
    # links只是一条记录
    current_time_stamp = time.time()

    local_time_struct = time.localtime(current_time_stamp)
    # 提取小时、分钟、秒
    hour = local_time_struct.tm_hour
    minute = local_time_struct.tm_min
    second = local_time_struct.tm_sec
    hrandom = random.randint(1, 30)
    if minute%10==0 and second>30:
            conn.close()
            conn=pool.get_connection()
            time.sleep(60-second)
    cursor=None  
    try:
        cursor=conn.cursor()
    except Exception as e:
        print('连接数据库出错',e)
        try:
            conn.close()
            
        except Exception as e:
            print('连接数据库出错',e)
        conn=pool.get_connection()
        cursor=conn.cursor()    
    
    ali_whitelist = getwhitelist(conn, 'ali')
    ebay_whitelist = getwhitelist(conn, 'ebay')
    data_to_insert = []
    # 每个关键词一条记录
    sql = 'select currency_simplename,rate from rates'
    cursor_c = conn.cursor()
    cursor_c.execute(sql)
    rates = cursor_c.fetchall()
    ratedict = []
    for rowr in rates:
        ratedict.append({"currency_simplename": rowr[0], "rate": rowr[1]})
    # link=links
    shop_type = link['shoptype']
    keywords = link['key']
    usernames = link['username']
    linksinner = link['links']
    keywordshis = keywords
    
    for kindex,     lkx in enumerate( linksinner):
        try:
            productid = lkx['productId']
            currency = 'US'
            # print(productid)
            if shop_type == 'ebay':
                if productid=='123456':
                    # print(lkx)
                    continue
                #if shop_type=='ali' url.split('/')[-1]
                storename = lkx['seller']
                # strstore = storename
                # storename = strstore.split('/')[-1]
                # storename = f'{storename}{splitchar}{strstore}'
                title = lkx['title']
                itemlink = f'https://www.ebay.com/itm/{productid}'
                pic = lkx['image_url']
                pricex = lkx['price']

                currencyx = re.findall(r'[A-Za-z]+', pricex)
                # print(currencyx)
                matches = re.findall(r'[^\d.,\s]+', str(pricex))
                currencyx=''.join(matches)
                currency = currencyx
                # 获取数字部分
                price2 = re.findall(r'\d+\.\d+', pricex)
                # print(price2)
                price = price2[0]
                priceshipping=0
                memo=''
                try:
                    match = re.search(r'[\$]?([\d,]+\.?\d*)', lkx['shipping'])
                    if match:
                        # 使用group(1)获取第一个捕获组的内容（数字部分）
                        priceshipping=float(match.group(1).replace(',', ''))
                        fdiscount=0
                        
                        # price= f"{float(price)+ float( priceshipping    )}"
                        memo=f"{lkx['shipping']} -》 {lkx['condition']}  -> {lkx['location']}"
                except Exception as e:
                    # print('出错了，',shop_type,e)
                    memo=memo + ' '
            if shop_type == 'ali':
                storename=''
                try:
                    storename = f"{lkx['store']['storeName']} {splitchar}  {lkx['store']['storeUrl'].replace('//','')}"
                except Exception as e:
                    print('ali找storename',e)

                title = lkx['title']['displayTitle']
                itemlink = f'https://www.aliexpress.com/item/{productid}.html'
                pic ='https:' + lkx['images'][0]['imgUrl']
                price = lkx['prices']['salePrice']['minPrice']
                currency=lkx['prices']['currencySymbol']
            # # 对于爬虫到的数据，写入followprice lkx['currencySymbol']
            # 一条skukeywords记录，可能有2条爬虫记录，分别是阿里，ebay
            # # 如果不是第一次抓取，抓取很多次了。
            # 抓取后，首先判断是否抓取过了，如果抓取过了，是否有变化，如果有变化，就要记录如历史数
            # 输入为抓取传输过来的数据
            if currency.upper() != 'US' and currency.upper() != '$':
                try:
                    for cur in ratedict:
                        if cur['currency_simplename'].lower() == currency.lower():
                            price = f'{float(price) / float(cur['rate']):.2f}'  
                            break
                except Exception as e:
                    print(kindex,productid,e)
            if dictexists(ali_whitelist, storename) and shop_type == 'ali':
                continue
            if    shop_type == 'ebay':
                if dictexists(ebay_whitelist,storename):
                        continue
            for username in usernames:
                sql = f"select id,title,pic,price,productid from follow_price where productid = '{productid}' and username='{username}' "
                cursor.execute(sql)
                # print(sql)
                results_b = cursor.fetchall()
                intchanged = 0
                if results_b:
                    idf = results_b[0][0]
                    print(keywords,'->序号：',kindex,'已经有数据了���productid:',productid,'->username:',username)
                    title2 = results_b[0][1]
                    pic2 = results_b[0][2]
                    price2 = results_b[0][3]
                    # pic=最新抓取到的图片
                    intchanged = 0
                    sql = f"update  follow_price set  opdate=now() "
                    strq = ','
                    if pic2 != pic:
                        sql += f" ,pic='{pic}',pic2='{pic2}'"
                        intchanged = 1
                    if title != title2:
                        sql += f" ,title='{title}',title2='{title2}'"
                        intchanged = 1
                    diff = abs(float(price2) -
                                float(price))  # 使用abs函数获取差值的绝对值，避免因顺序问题导致结果为负
                    # if diff > 0.01:
                    #     print("两个浮点数的差超过了0.01")
                    # else:
                    #     print("两个浮点数的差未超过0.01")
                    if diff > 0.01:
                        sql += f' ,price={price},price2={price2}'
                        intchanged = 1
                    if intchanged == 1:
                        sql += f' ,hasexcept="有异常"'
                    sql += f"  where id={idf}"
                    if intchanged == 1:
                        print(sql)
                        cursor.execute(sql)
                        conn.commit()
                        data_to_insert.append(sql)
                        sql = f""" insert into follow_price_history(username,productid,shop_type,storename,keywords,title,link,pic,price,followstatus,opdate) values(  '{username}','{productid}','{shop_type}','{storename}','{keywords}','{title}','{itemlink}','{pic}',{price},'未跟价',now())"""
                        data_to_insert.append(sql)
                        cursor.execute(sql)
                else:
                    # 需要插入记录
                    print(keywords,'->序号：',kindex,'没有数据，需要插入。productid:',productid,'->username:',username)
                    sql = f""" insert into follow_price(username,productid,shop_type,storename,keywords,title,link,pic,price,currency,followstatus,opdate)     values(           '{username}','{productid}','{shop_type}','{storename}','{keywords}','{title}','{itemlink}','{pic}',{price},'{currency}','未跟价',now())"""
                    data_to_insert.append(sql)
                    print(sql)
                    cursor.execute(sql)
                    conn.commit()
                    sql = f""" insert into follow_price_history(username,productid,shop_type,storename,keywords,title,link,pic,price,currency,followstatus,opdate)     values(  '{username}',   '{productid}','{shop_type}','{storename}','{keywords}','{title}','{itemlink}','{pic}',{price},'{currency}','未跟价',now())"""
                    print(sql)
                    data_to_insert.append(sql)
                    cursor.execute(sql)
                    conn.commit()
        except Exception as e:
            print('process_2->出现异常',e)
    for usr in usernames:
        sql = f"""insert into sku_keywords_history(username,id,sku,keywords,ebay,ALI,chargeman,opdate,capturetimes) 
                    select username,id,sku,keywords,ebay,ALI,chargeman,now(),1 from sku_keywords where keywords = '{keywordshis}' and username='{usr}'"""
        data_to_insert.append(sql)
        cursor.execute(sql)
        conn.commit()
        print(sql)
    current_time_stamp = time.time()
    # 将时间戳转换为本地时间的结构体
    local_time_struct = time.localtime(current_time_stamp)
    # 提取小时、分钟、秒
    hour = local_time_struct.tm_hour
    minute = local_time_struct.tm_min
    second = local_time_struct.tm_sec
    hrandom = random.randint(1, 30)
    print(keywords,'(关键词)->（店铺）',shop_type, f"当前时间是：{hour}时{minute}分{second}秒")
    # for stmt in data_to_insert:
    #     print(stmt)
    #     cursor.execute(stmt)
    conn.commit()
    cursor.close()
    cursor_c.close()



    
         
def get_time_diff(conn):
    # 获取当前时间
    try:
  
        current_time_stamp = time.time()
        # 将时间戳转换为本地时间的结构体
        local_time_struct = time.localtime(current_time_stamp)
        # 提取小时、分钟、秒
        hour = local_time_struct.tm_hour
        minute = local_time_struct.tm_min
        second = local_time_struct.tm_sec
        hrandom = random.randint(1, 30)
        print(f"当前时间是：{hour}时{minute}分{second}秒")
        current_date = datetime.now().date()
        target_date = current_date + timedelta(days=0)
        t8=datetime.combine(target_date, datetime_time(1, 0, 0))
        t11=datetime.combine(target_date, datetime_time(11, 0, 0))
        t20=datetime.combine(target_date, datetime_time(13, 0, 0))
        t23=datetime.combine(target_date, datetime_time(16, 0, 0))
        t1=None
        t2=None
        if hour <=11 and hour >=8:
             t1=t8
             t2=t11
        elif hour <=23 and hour >=17:
             t1=t20
             t2=t23         
        cursor=conn.cursor()
        current_time = datetime.now()
        print(current_time)
        
        query = """
                SELECT opdate 
                FROM sku_keywords_history 
                WHERE opdate BETWEEN %s AND %s
                """
        cursor.execute(query, (t1, t2))
    

        results = cursor.fetchall()
        
        # 返回结果
        return [(row[0]) for row in results]
                
    except Exception as e:
        print(f"错误: {str(e)}")
        return None

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        print(1)  # 你的代码
        
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     window = MainWindow()
#     window.show()
#     sys.exit(app.exec_())

# if __name__ == '__main__':
#     print(1)
#     # input("按回车键退出...")  # 等待用户输入
#     conn=getconn()
#     ebay_whitelist = white_list_cache.get_white_list(conn, 'ebay')
#     node_manager = NodeManager(conn)
#     if node_manager.update_node_status():
#         print("Node status updated successfully")
#     else:
#         print("Failed to update node status")
#     #     input("按回车键退出...")  # 等待用户输入
# # #     aa=get_time_diff(conn)
# #     print(aa)
# #     # print(1)
#     downloaddata(conn)
#     # # 搜素词
# app = QApplication(sys.argv)
# ex = Crawl()
# # ex.start_button.click()

# # 设置窗口的宽度为400像素，高度这里暂时使用默认值，你可以根据需要自行调整
# ex.setGeometry(0, 0, 400, 400)
# sys.exit(app.exec_())
# print("已暂停，started变量值为:", self.started)
